<template>
    <n-config-provider>
        <n-card title="" size="medium">
            <n-space vertical :size="24">
                <n-space :wrap="false" :wrap-item="false" :size="16" style="display: flex">
                    <!-- 每个表单项容器 -->
                    <div class="box">
                        <p>机场名称：</p>
                        <n-input v-model:value="flyName" type="text" placeholder="请输入任务名称" 
                        size="medium" clearable style="width: 80%"/>
                        <n-button 
                            v-show="flyName"
                            @click="flyName = ''" 
                            type="error" 
                            tertiary 
                            size="small"
                        >X</n-button>
                    </div>
                    <div class="box">
                        <p>机场状态：</p>
                        <n-select v-model:value="flyType" size="medium" 
                        :options="flyTypeOptions" style="width: 80%"/>
                        <n-button 
                            v-show="flyType"
                            @click="flyType = ''" 
                            type="error" 
                            tertiary 
                            size="small"
                        >X</n-button>
                    </div>
                    <div class="box">
                        <p>机场启用：</p>
                        <n-select v-model:value="flyStatus" size="medium" 
                        :options="flyStatusOptions" style="width: 80%"/>
                        <n-button 
                            v-show="flyStatus"
                            @click="flyStatus = ''" 
                            type="error" 
                            tertiary 
                            size="small"
                        >X</n-button>
                    </div>
                </n-space>
                <n-space :wrap="false" :wrap-item="false" :size="16" style="display: flex">
                    <div class="box">
                        <n-button type="info" size="medium" @click="clickAdd">新增</n-button>
                        <n-button type="primary" size="medium" @click="handleSearch">搜索</n-button>
                    </div>
                </n-space>
            </n-space>
        </n-card>
        <n-data-table
        :columns="columns"
        :data="tasklist"
        :pagination="pagination"
        :bordered="true"
        style="margin-top: 4px;"
        />
        <!-- 右侧抽屉 -->
        <n-drawer v-model:show="active" :width="400" placement="right" @after-leave="handelboot">
            <n-drawer-content :title="islook?'查看信息':'编辑信息'">
                <flyshowForm :row-data="taskdata" :is-look="islook" @task-list="handelboot"/>
            </n-drawer-content>
        </n-drawer>
    </n-config-provider>
</template>

<script setup>
import { 
    NDrawer,
    NDrawerContent,
    NButton,
    NConfigProvider,
    NGrid,
    NGridItem,
    NCard,
    NInput,
    NSpace, 
    NSelect,
    NDatePicker,
    NDataTable,
    useDialog,
    NSwitch,
    useMessage,
} from 'naive-ui'
import flyshowForm from './flyshowForm.vue';
import { h, ref, computed } from 'vue';
import { taskDeleteApi, taskListApi, taskPostApi } from '../../api/task';
const dialog = useDialog();
const flyName = ref('')
const flyType = ref('')
const flyStatus = ref('')
const taskTindex = ref('')
const starttime = ref(null)  // 默认值改为空
const endtime = ref(null)    // 默认值改为空
const active = ref(false)
const islook = ref(true)
const flyTypeOptions = [
    { label: '全部', value: '1' },
    { label: '在线', value: '2' },
    { label: '离线', value: '3' },
]
const flyStatusOptions = [
    { label: '全部', value: '1' },
    { label: '启用', value: '2' },
    { label: '禁用', value: '3' }, 
]
// 表格配置
function createColumns({
  look,
  del,
  edit
  }) {
    return [
      {
        title: "序号",
        key: "_id",
        width: 70,
        ellipsis: {
          tooltip: true
        }
      },
      {
        title: "机场名称",
        key: "name",
      },
      {
        title: "机场简介",
        key: "type",
      },
      {
        title: "关联机场数量",
        key: "count",
      },
      {
        title: "启用",
        key: "boot",
        render(row) {
          return h(
            NSwitch,
            {
              value: row.boot,
              "onUpdate:value": (newValue) => {
                row.boot = newValue
              }
            }
          )
        }
      },
      {
        title: "操作",
        key: "actions",
        width: 230,
        render(row) {
          const btns=[
            {title:'查看',type:'primary',fuc:()=>{look(row);}},
            {title:'编辑',type:'info',fuc:()=>{edit(row)}},
            {title:'删除',type:'Error',fuc:()=>{del(row)}},
          ]
          const btnsNode = btns.map((item)=>{
            return h(
              NButton,
              {type:item.type,onClick:item.fuc,style:{ margin:'5px'}},
              { default: () => item.title}
            )
          })
          return btnsNode
        }
      }
    ];
  };

// 使用消息组件
const message = useMessage()
message.warning('当前页面功能处于测试阶段，暂未开放，请谨慎使用！')
// 备份原始数据
const originalTasklist = ref([])

// 获取表格数据
const tasklist = ref([])
taskListApi().then(res=>{
  console.log(res.data.data);
  originalTasklist.value = res.data.data
  tasklist.value = res.data.data
})

// 搜索功能实现
const handleSearch = () => {
  // 触发计算属性更新
  tasklist.value = filteredTasks.value
}

const filteredTasks = computed(() => {
  return originalTasklist.value.filter(task => {
    // 名称匹配（空值时视为匹配成功）
    const nameMatch = flyName.value 
      ? task.name.toLowerCase().includes(flyName.value.toLowerCase())
      : true
    console.log('task.type', task.type);
    console.log('flyType.value', flyTypeOptions.find(opt => opt.value == flyType.value)?.label || flyType.value);
    // 类型匹配
    const typeMatch = flyType.value 
      ? task.type === flyTypeOptions.find(opt => opt.value == flyType.value).label
      : true
    console.log('typeMatch', typeMatch);
    
    // 状态匹配
    const statusMatch = flyStatus.value 
      ? task.status === flyStatusOptions.find(opt => opt.value == flyStatus.value).label
      : true

    // 周期匹配
    const tindexMatch = taskTindex.value 
      ? task.time === taskT.find(opt => opt.value == taskTindex.value).label
      : true

    // 日期范围匹配（需同时存在起止时间）
    const dateMatch = starttime.value && endtime.value
      ? new Date(task.starttime) >= new Date(starttime.value) &&
        new Date(task.endtime) <= new Date(endtime.value)
      : true
    // console.log('匹配结果', {
    //     name: task.name,
    //     searchName: flyName.value,
    //     nameMatch,
    //     typeMatch,
    //     statusMatch,
    //     tindexMatch,
    //     dateMatch
    // })
    // 所有条件同时满足
    return nameMatch && typeMatch && statusMatch && tindexMatch && dateMatch
  })
})

// 定义抽屉数据
const taskdata =ref(null)
const columns = createColumns({
    look(row) {
        active.value = true
        taskdata.value = row 
    },
    edit(row) {
        islook.value = false
        active.value = true
        taskdata.value = row
    },
    async del(row) {    
        console.log('删除');
        dialog.warning({
            title: "警告，删除后无法找回",
            content: `你确定要删除 ${row.name} 吗？`,
            positiveText: "确定",
            negativeText: "取消",
            draggable: true,
            onPositiveClick: async() => {
                console.log(row._id);
                let res = await taskDeleteApi(row._id)
                console.log(res);
                if(res.data.code==1){
                console.log(tasklist);
                
                let list = tasklist.value.filter(item=>item._id!=row._id)
                tasklist.value = list //更新本地
              }
            },
        });
    }
});

// 日期格式化
const formatDate = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}
// 子组件数据返回
const handelboot = (formData) => {
    active.value = false
    islook.value = true
    // 无数据则返回
    if(!formData) return
    console.log('接收到子组件数据',formData);

    // 格式化日期
    formData.starttime = formatDate(formData.starttime)
    formData.endtime = formatDate(formData.endtime)

    let len = tasklist.value.length
    for(let i = 0;i<len;i++){
      if(tasklist.value[i]._id == formData._id){
        tasklist.value[i] = formData //替换原数据
        //将子组件数据渲染到表格，并做格式转换
        tasklist.value[i].type = flyTypeOptions.find(opt => opt.value == tasklist.value[i].type)?.label || tasklist.value[i].type
        tasklist.value[i].time = taskT.find(opt => opt.value == tasklist.value[i].time)?.label || tasklist.value[i].time
        tasklist.value[i].status = flyStatusOptions.find(opt => opt.value == tasklist.value[i].status)?.label || tasklist.value[i].status
        return
      }
    }
    tasklist.value.push(formData) //新增数据
}
// 新增
const clickAdd = async() => {
  // 获取数据并且中格式转换
  let model = ref({
    name: flyName,
    type: flyTypeOptions.find(opt => opt.value == flyType.value)?.label || flyType.value,
    time: taskT.find(opt => opt.value == taskTindex.value)?.label || taskTindex.value,
    status: flyStatusOptions.find(opt => opt.value == flyStatus.value)?.label || flyStatus.value, 
    starttime:formatDate(starttime.value),
    endtime:formatDate(endtime.value),
    count:'',
  })
  // 调用接口
  let res =await taskPostApi(model.value)
  console.log(res);
  tasklist.value.push({_id:res.data._id,...model.value})
}
// 分页器
const pagination = ref({
    pageSize: 4,
})

</script>

<style>
p{
    width: 90px;
}
.box{
    flex: 1; 
    display: flex; 
    align-items: center;
    gap: 8px;
}
/* 表格数据的行高 */
.n-data-table .n-data-table-tbody .n-data-table-tr {
  height: 20px; /* 设置你想要的行高 */
}
</style>